#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2014年10月9日

@author: chenyongbing
'''
import urllib,urllib2,re
from lxml import etree
from localConfig import LocalConfig
myLocalConfig = LocalConfig()
import datetime,os
class AnalyzeConfig(object):
    u'''
        解析前端配置文件。
    '''


    def __init__(self, baseUrl=None,config_file=None):
        '''
        Constructor
        '''
        if baseUrl==None and config_file==None:
            baseUrl = 'http://retail.zhimatech.com/api/config_template'
        self.baseUrl = baseUrl
        if baseUrl!=None:
            while 1:
                try:
                    self.root = self.getHtmlSource()
                    break
                except:continue
        elif config_file!=None:
            self.root = etree.XML(open(config_file).read())
        else:
            self.baseUrl = myLocalConfig.config_url
            self.root = self.getHtmlSource()
    def getHtmlSource(self):
        t = datetime.datetime.today().strftime('%Y%m%d')
        config_file = re.sub('/[^\/]+$','',myLocalConfig.config_file) + '/' + 'config_template.xml'
        xfile =config_file +'.%s'%t
        if os.path.exists(xfile):
            root = etree.XML(open(xfile).read())
        else:
            response = urllib2.urlopen(self.baseUrl)
            html = response.read()
            try:
                root = etree.XML(html)
                fr = open(xfile,'w')
                fr.write(html)
                fr.close()
            except:
                root = etree.XML(open(config_file).read())
            #raise u'配置文件格式问题'
        return root
    
    def getDevices(self,groups=[]):
        devices = []
        for group in groups:
            group_node = self.root.find('.//group[@id="%s"]'%group)
            if group_node is None:
                errMsg = u'Group Id:%s不存在'%shop_group
            else:
                for dev_node in group_node.findall('.//device'):
                    device = dev_node.get('id')
                    if device not in devices:devices.append(device)
        return devices
    def getDevicesByshop_group(self,shop_group=None,shop_name=None):
        devices = []
        errMsg = ''
        if shop_group!=None:
            group_node = self.root.find('.//group[@id="%s"]'%(shop_group))
            if group_node is None:
                errMsg = u'门店ID:%s不存在'%shop_group
        elif shop_name!=None:
            group_node = self.root.find('.//group[@name="%s"]'%(shop_name))
            if group_node is None:
                errMsg = u'门店名:%s不存在'%shop_name
        
        if group_node is not None:
            shop_group = group_node.get('id')
            shop_name = group_node.get('name')
            for dev_node in group_node.findall('.//device'):
                device = dev_node.get('id')
                
                #print shop_group,device
                if device not in devices:
                    devices.append(device)
        
        if errMsg=='':
            return {'group':shop_group,'name':shop_name,'devices':devices}
        else:
            return {'errMsg':errMsg}
    def getGroupName(self,shop_group=None,device=None):
        if shop_group!=None:
            group_node = self.root.find('.//group[@id="%s"]'%shop_group)
            if group_node  is  not None:
                group_name = group_node.get('name')
                return group_name
            else:
                return ''
        elif device!=None:
            dev_node = self.root.find('.//device[@id="%s"]'%device)
            if dev_node is not None:
                group_node = dev_node.getparent()
                group_name = group_node.get('name')
                return group_name
            else:
                return ''
        else:
            return ''
    def getComp(self,comp_name=None,comp_group=None,shop_name=None,shop_group=None,device=None):
        groups = []
        errMsg = ''
        time_walkby_duration = self.root.find('.//system/params/param[@name="time_walkby_duration"]').get('value')
        quartz_source_migrate_period = self.root.find('.//system/params/param[@name="quartz_source_migrate_period"]').get('value')
        role_wifi_min_rssi = self.root.find('.//system/params/param[@name="role_wifi_min_rssi"]').get('value')
        role_customer_min_rssi = self.root.find('.//system/params/param[@name="role_customer_min_rssi"]').get('value')
        if (comp_group!=None or comp_name!=None) and shop_group==None:
            if comp_group!=None:
                comp_node = self.root.find('.//groups/group[@id="%s"]'%comp_group)
                if comp_node is None:
                    errMsg = u'公司ID:%s不存在'%comp_group
            elif comp_name!=None:
                comp_node = self.root.find('.//groups/group[@name="%s"]'%comp_name)
                if comp_node is None:
                    errMsg = u'公司名:%s 不存在'%comp_name
            if comp_node is not None:
                for group_node in comp_node.findall('.//group[@type="4"]'):
                    group = group_node.get('id')
                     
                    groupMsgs = self.getDevicesByshop_group(shop_group=group,shop_name=shop_name)
                     
                    groups.append(groupMsgs)
  
        elif (shop_group!=None or shop_name!=None) and device==None:
            
            groupMsgs = self.getDevicesByshop_group(shop_group=shop_group,shop_name=shop_name)
            if 'errMsg' not in groupMsgs:
                groups.append(groupMsgs)
            else:
                errMsg = groupMsgs['errMsg']
        elif device!=None:
            dev_node = self.root.find('.//device[@id="%s"]'%(device))
            if dev_node is None:
                errMsg = u'设备ID:%s不存在'%device
            if dev_node is not None:
                group_node = dev_node.getparent()
                group = group_node.get('id')
                groupMsgs = self.getDevicesByshop_group(group)
                
                if 'errMsg' not in groupMsgs:
                    groups.append(groupMsgs)
                else:
                    errMsg = groupMsgs['errMsg']
        else:
            for group_node in self.root.findall('.//group[@type="4"]'):
                group = group_node.get('id')
                 
                groupMsgs = self.getDevicesByshop_group(shop_group=group,shop_name=shop_name)
                 
                groups.append(groupMsgs)
        if errMsg!='':
            return {'groupMsgs':groups,'errMsg':errMsg}
        else:
            return {'groupMsgs':groups}
                    

    def getShopGroups(self,groupId=None):
        groups = []
        if groupId==None:
            for group_node in self.root.findall('.//group[@type="4"]'):
                group = group_node.get('id')
                groups.append(group)
        else:
            for node in self.root.findall('.//group[@id="%s"]'%groupId):
                for group_node in node.findall('.//group[@type="4"]'):
                    group = group_node.get('id')
                    groups.append(group)
        return groups
            
    def getGroupsDevices(self,groupId=None):
        GroupsDevices = {}
        if groupId==None:
            for group_node in self.root.findall('.//group[@type="4"]'):
                group = group_node.get('id')
                devices = []
                for device_node in group_node.findall('.//device'):
                    device = device_node.get('id')
                    devices.append(device)
                if len(devices)!=0:
                    #print group,','.join(devices)
                    GroupsDevices[group] = devices
        else:
            for group_node in self.root.findall('.//group[@id="%s"]'%groupId):
                group = group_node.get('id')
                devices = []
                for device_node in group_node.findall('.//device'):
                    
                    device = device_node.get('id')
                    devices.append(device)
                if len(devices)!=0:
                    #print group,','.join(devices)
                    GroupsDevices[group] = devices
        return GroupsDevices
    
    
    

    
    def get_group_and_name_list(self):
        groupRet = self.getComp()
        if 'errMsg' in groupRet.keys():
            errMsg = groupRet['errMsg']
        groupMsgs = groupRet['groupMsgs']
        datas = []
        
        for groupMsg in groupMsgs:
            group = groupMsg['group']
            name = groupMsg['name']
            datas.append([group,name])
        return datas
if __name__=="__main__":
    import sys
    config_file = '../conf/config_template.xml'
   # baseUrl = 'http://retail.zhimatech.com/api/config_template'
    comp_group = 32010199
    comp_name = u'维玛'
    shop_group = 32010331
    shop_name = u'金宝汇店 Pro'
    device = '048d385650f8'
    myAnalyzeConfig = AnalyzeConfig(baseUrl=None,config_file=None)
    #print myAnalyzeConfig.get_group_and_name_list()
    print type(myAnalyzeConfig.getGroupName(shop_group=shop_group))
    #print len(myAnalyzeConfig.getDevices(groups=[32010464]))
#     myAnalyzeConfig.getGroupsDevices()
#     #sys.exit()
#     print myAnalyzeConfig.getGroupName(shop_group=shop_group)
#     sta =  myAnalyzeConfig.getComp(shop_group=shop_group)
#     if 'errMsg' in sta.keys():
#         print sta['errMsg']
    #print '--',sta['groupMsgs']